package com.daocao.jy.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.daocao.jy.R;
import com.daocao.jy.activity.AMapActivity;
import com.daocao.jy.activity.CityListSelectActivity;
import com.daocao.jy.activity.NowRechargeActivity;
import com.daocao.jy.activity.PacketRechargeActivity;
import com.daocao.jy.activity.ProvinceSelectActivity;
import com.daocao.jy.activity.WebViewActivity;
import com.daocao.jy.adapter.HomeServiceAdapter;
import com.daocao.jy.api.Api;
import com.daocao.jy.api.model.IndexModel;
import com.daocao.jy.base.PermissionActivity;
import com.daocao.jy.util.GlideImageLoader;
import com.daocao.jy.util.Network;
import com.daocao.jy.util.RxLifeUtil;
import com.daocao.jy.util.ToastUtil;
import com.daocao.jy.util.Util;
import com.daocao.jy.view.CustomViewPager;
import com.daocao.jy.view.LoginDialog;
import com.daocao.jy.view.NoticeView;
import com.daocao.jy.view.RightIconText;
import com.lljjcoder.citylist.bean.CityInfoBean;
import com.viewpagerindicator.LinePageIndicator;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-4.
 */

public class MainHomeFragment extends BaseFragment implements AMapLocationListener {

    @BindView(R.id.txt_address_title)
    TextView txtAddressTitle;
    @BindView(R.id.txt_location)
    TextView txtLocation;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.txt_notice)
    NoticeView txtNotice;
    @BindView(R.id.img_msg_tips)
    ImageView imgMsgTips;
    @BindView(R.id.view_red)
    View viewRed;
    @BindView(R.id.txt_price_92)
    RightIconText txtPrice92;
    @BindView(R.id.txt_price_95)
    RightIconText txtPrice95;
    @BindView(R.id.txt_price_0)
    RightIconText txtPrice0;
    @BindView(R.id.txt_instant_tips)
    TextView txtInstantTips;
    @BindView(R.id.txt_instant_tips_two)
    TextView txtInstantTipsTwo;
    @BindView(R.id.btn_rechare_share)
    SuperButton btnRechareShare;
    @BindView(R.id.btn_oil_recharge)
    TextView btnOilRecharge;
    @BindView(R.id.txt_term_tips)
    TextView txtTermTips;
    @BindView(R.id.txt_term_tips_two)
    TextView txtTermTipsTwo;
    @BindView(R.id.btn_packet_share)
    SuperButton btnPacketShare;
    @BindView(R.id.btn_packet_oil)
    TextView btnPacketOil;
    @BindView(R.id.indicator)
    LinePageIndicator indicator;
    @BindView(R.id.pager)
    CustomViewPager pager;
    @BindView(R.id.list)
    RecyclerView list;
    //    @BindView(R.id.banner)
//    Banner banner;
    @BindView(R.id.index_banner)
    Banner banner;
    private Unbinder unbinder;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private HomeServiceAdapter adapter;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_main_home;
    }

    @Override
    protected void initView() {
//        dialog = new LoginDialog(getContext());
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initLocation();
                getIndex();
            }
        });
        initLocation();
        List<String> stringList = new ArrayList<>();
        stringList.add("我是测试一号");
        stringList.add("我是测试二号");
        stringList.add("我是测试三号");
        txtNotice.setList(stringList);
        adapter = new HomeServiceAdapter(getContext());
        list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        list.setAdapter(adapter);
        banner.setImageLoader(new GlideImageLoader());
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        getIndex();
    }


    private void initLocation() {

//        if (mlocationClient == null) {
        //初始化定位
        mlocationClient = new AMapLocationClient(getContext());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位回调监听
        mlocationClient.setLocationListener(this);
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//        }
        checkPermission(new PermissionActivity.CheckPermListener() {
            @Override
            public void superPermission() {
                mlocationClient.startLocation();
            }
        }, R.string.location_permission, R.string.get_location, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
        unbinder.unbind();
    }

    public void setLocation(String city) {
        txtLocation.setText(city);
    }

    public void getIndex() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        if (refresh != null) {
            refresh.setRefreshing(true);
        }
        Api.api_service.getIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    private void setData(IndexModel.DatasBean item) {
        txtPrice0.setTextString(item.price._$0216);
        txtPrice92.setTextString(item.price._$92104);
        txtPrice95.setTextString(item.price._$95147);

        txtInstantTips.setText(item.instant.title + "\n" + item.instant.desc);
        txtInstantTipsTwo.setText(item.instant.note);
        btnOilRecharge.setText(item.instant.btn);

        txtTermTips.setText(item.term.title + "\n" + item.term.desc);
        txtTermTipsTwo.setText(item.term.note);
        btnPacketOil.setText(item.term.btn);

        adapter.update(item.services);


        if (item.index_banner == null) {
            return;
        }
        List<String> bannerdata = new ArrayList<>();
        for (int i = 0; i < item.index_banner.size(); i++) {
            bannerdata.add(item.index_banner.get(i).icon);
        }
        banner.setImages(bannerdata).setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (TextUtils.isEmpty(item.index_banner.get(position).url)) {
                    return;
                }
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("url", item.index_banner.get(position).url);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
            }
        }).start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                CityInfoBean cityInfoBean = bundle.getParcelable("cityinfo");
                txtLocation.setText(cityInfoBean.getName());
            }
        }
    }

    @OnClick({R.id.txt_location, R.id.img_msg_tips, R.id.btn_rechare_share, R.id.btn_oil_recharge, R.id.btn_packet_share, R.id.btn_packet_oil})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_location:
//                Intent citySelect = new Intent(getActivity(), CityListSelectActivity.class);
//                startActivityForResult(citySelect, 100);
//                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                Util.startActivity(getActivity(), ProvinceSelectActivity.class);
                break;
            case R.id.img_msg_tips:
                Util.startActivity(getActivity(), AMapActivity.class);
                break;
            case R.id.btn_rechare_share:
                break;
            case R.id.btn_oil_recharge:
                Util.startActivity(getActivity(), NowRechargeActivity.class);
                break;
            case R.id.btn_packet_share:
                break;
            case R.id.btn_packet_oil:
                Util.startActivity(getActivity(), PacketRechargeActivity.class);
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (refresh != null) {
            refresh.setRefreshing(false);
        }
        if (amapLocation.getErrorCode() == 0) {
            txtLocation.setText(amapLocation.getCity());
        } else {
            String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
            ToastUtil.makeText(getContext(), errText);
        }
    }
}
